//用户强制修改
/**
 * 强制修改用户视图模型
 */
interface IUserReviseDetailViewModel extends IUserDetailViewModel{
    /**
     * 角色
     */
    rolesCheckedList: Array<string>;

    /**
     * 上传图片工具（是否隐藏）：实名头像
     */
    realHeadUpload : boolean;
    /**
     * 上传图片工具（是否隐藏）：身份证
     */
    idCardUpload : boolean;
    /**
     * 上传图片工具（是否隐藏）：驾驶证
     */
    drivingLicenseUpload : boolean;    
    /**
     * 上传图片工具（是否隐藏）：行驶证
     */
    vehicleLicenseUpload : boolean;

    /**
     * 实名头像上传图片
     */
    uploaderRealHead:(submitUri:string, selectedFile:any,result:string) => void;
    /**
     * 身份证上传图片
     */
    uploaderIdCard:(submitUri:string, selectedFile:any,result:string) => void;
    /**
     * 驾驶证上传图片
     */
    uploaderDrivingLicense: (submitUri:string, selectedFile:any,result:string) => void;
    /**
     * 行驶证上传图片
     */
    uploaderVehicleLicense: (submitUri:string, selectedFile:any,result:string) => void;
    /**
     * SAS Url
     */
    sasUrl: string;
    /**
     * 提交图片url
     */
    submitRealHeadUrl: string;
    submitIdCardUrl: string;
    submitDrivingLicenseUrl: string;
    submitVehicleLicenseUrl: string;
    /**
     * 上传图片文件内容
     */
    selectedFileRealHead: any;
    selectedFileIdCard: any;
    selectedFileDrivingLicense: any;
    selectedFileVehicleLicense: any;
    /**
     * 保存
     */
    click: () => void;
}
/**
 * 模型视图
 */
interface IUserReviseViewModel extends IBaseViewModel<IUserReviseQueryTerms>{
    /**
     * 角色多项勾选
     */
    rolesList: Array<RolesListItemResponse>;
    /**
     * ui-grid控制
     */
    gridOptions: uiGrid.IGridOptionsOf<UserListItemResponse>;
    /**
     * 强制修改用户视图
     */
    detail: IUserReviseDetailViewModel;
    /**
     * 强制修改用户
     */
    reviseUser: (user: UserListItemResponse) => void;
}
/**
 * 查询条件
 */
interface IUserReviseQueryTerms{
    /**
     * 关键字
     */
    searchingKeyWord: string;
    /**
     * 车牌号
     */
    searchingCarCode: string;
    /**
     * 起始时间
     */
    searchingStartTime: Date;
    /**
     * 结束时间
     */
    searchingEndTime: Date;
    /**
     * 角色
     */
    searchingRoleId: string;
    /**
     * 实名认证状态
     */
    searchingState: number;
    /**
     * 缓存
     */
    useCache: boolean;
}

class UserReviseController extends ListController<IUserReviseViewModel,IUserReviseQueryTerms>{
    gridApi: uiGrid.IGridApiOf<UserListItemResponse>;

    constructor($scope: IUserReviseViewModel, private userService: IUserService, private rolesService: IRolesService, private valueService: IValueService, private storageService: IStorageService, $ngBootbox: BootboxService, private azureBlob: any, private $stateParams:any)
    {
        super($scope);
    }

    init(): void{
        super.init();
        this.$scope.reviseUser = this.showReviseUserDialog;
        this.queryTerms = {
            searchingKeyWord:"",
            searchingCarCode:"",
            searchingStartTime:moment("0001-01-01").toDate(),
            searchingEndTime:new Date(),
            searchingRoleId:"",
            searchingState:null,
            useCache:false
        };

         this.$scope.gridOptions = {
            enableSorting: false,
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            paginationPageSizes: [10,20,30],
            columnDefs: [
                {name: "序号", field: "index", enableColumnMenu: false},
                {name: "车牌号", field: "carNumber", enableColumnMenu: false},
                {name: "车型", field: "carType", enableColumnMenu: false},
                {name: "车长", field: "carLength", enableColumnMenu: false},
                {name: "用户名", field: "userName", enableColumnMenu: false},
                {name: "真实姓名",field: "realNameState",enableColumnMenu:false},
                {name: "实名认证状态",field: "realNameState",enableColumnMenu:false},
                {name: "实名申请时间", field:"certificationTime",enableColumnMenu: false},
                {name:"禁用",field:"isLockedOut",enableColumnMenu:false},
                {name:"角色",field:"roles",enableColumnMenu:false},
                {
                    name: "操作",
                    cellFilter: "checkmark",
                    cellTemplate: '<a data-toggle="modal" data-target="#myModal" class="fa fa-edit m-l-xs primary text-info" title="编辑" ng-click="grid.appScope.reviseUser(row.entity)"></a>',
                    enableColumnMenu: false
                }
            ],
            onRegisterApi: (gridApi) => {
                this.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
            }
        };
        this.query();
        this.loadRolesCheckBox();
        this.showReviseUserDialog(this.$stateParams);
    }

    loadData(queryTerms: IUserQueryTerms, skip:number, count:number): void {
        this.userService.getList(queryTerms.searchingKeyWord,queryTerms.searchingCarCode,queryTerms.searchingStartTime,queryTerms.searchingEndTime,queryTerms.searchingRoleId,queryTerms.searchingState,queryTerms.useCache,skip,count).then(result => {
            this.$scope.gridOptions.totalItems = result.data.total;
            this.$scope.gridOptions.data = result.data.list;
            
            if(skip == 0){
                this.$scope.gridOptions.paginationCurrentPage = 1;
            }
            this.$scope.querying = false;
        }, error => {
            this.$scope.querying = false;
        });
    }
    /**
     * 加载roles角色下拉
     */
    loadRolesCheckBox():void{
        this.rolesService.getList().then(result =>{
            this.$scope.rolesList = result.data.list
        });
    }
    /**
     * 显示强制修改用户(编辑)
     */
    showReviseUserDialog(user: UserListItemResponse): void{
        this.userService.getDetail(user.userId).then(result =>{
            this.$scope.detail= {
                userId:user.userId,
                carCode:result.data.carCode,
                userName: user.realName || user.userName || user.phoneNumber,
                realHeadImageStatus: this.valueService.getCheckStateList().list[result.data.realHeadState].text,
                idCardImageSatus: this.valueService.getCheckStateList().list[result.data.idCardState].text,
                drivingLicenseImageStatus: this.valueService.getCheckStateList().list[result.data.drivingLincenseState].text,
                vehicleLicenseImageStatus:this.valueService.getCheckStateList().list[result.data.vehicleLicenseState].text,

                realHeadImage:result.data.realHeadImage,
                idCardImage:result.data.idCardImage,
                drivingLicenseImage:result.data.drivingLicenseImage,
                vehicleLicenseImage:result.data.vehicleLicenseImage,

                realHeadImageTool: result.data.realHeadState == 2 && result.data.realHeadImage !== null,
                idCardImageTool: result.data.idCardState == 2 && result.data.idCardImage !== null,
                drivingLicenseImageTool: result.data.drivingLincenseState == 2 && result.data.drivingLicenseImage !== null,
                vehicleLicenseImageTool: result.data.vehicleLicenseState == 2 && result.data.vehicleLicenseImage !==null,

                clickOkPassState:true,
                clickRemovePassState:true,

                clickIdCardOkPassState:true,
                clickIdCardRemovePassState:true,

                clickDrivingLicenseOkPassState:true,
                clickDrivingLicenseRemovePassState:true,

                clickVehicleLicenseOkPassState:true,
                clickVehicleLicenseRemovePassState:true,

                drivingLicenseCertificated:result.data.drivingLincenseState,
                realHeadImageCertificated:result.data.realHeadState,
                idCardCertificated:result.data.idCardState,
                vehicleLicenseCertificated:result.data.vehicleLicenseState,

                message: result.data.message,
                
                clickOk:this.clickOk,
                clickOkPass:this.clickOkPass,
                clickRemove:this.clickRemove,
                clickRemovePass:this.clickRemovePass,

                rolesCheckedList: this.rolesChecked(user.roles),

                realHeadUpload: result.data.realHeadState == 3 || result.data.realHeadState == 4 || result.data.realHeadImage !== null,
                idCardUpload: result.data.idCardState==3 || result.data.idCardState==4 || result.data.realHeadImage !==null,
                drivingLicenseUpload: result.data.drivingLincenseState == 3 || result.data.drivingLincenseState == 4 || result.data.drivingLicenseImage !==null,
                vehicleLicenseUpload: result.data.vehicleLicenseState == 3 || result.data.vehicleLicenseState == 4 || result.data.vehicleLicenseImage !==null,

                submitRealHeadUrl: '',
                submitIdCardUrl: "",
                submitDrivingLicenseUrl: '',
                submitVehicleLicenseUrl: '',

                selectedFileRealHead: null,
                selectedFileIdCard: null,
                selectedFileDrivingLicense: null,
                selectedFileVehicleLicense: null,

                sasUrl: this.getSasUrl(),
                
                uploaderRealHead: this.upload(this.$scope.detail.submitRealHeadUrl, this.$scope.detail.selectedFileRealHead, 'RealHead'),
                uploaderIdCard: this.upload(this.$scope.detail.submitIdCardUrl, this.$scope.detail.selectedFileIdCard, 'IDCard'),
                uploaderDrivingLicense: this.upload(this.$scope.detail.submitDrivingLicenseUrl,this.$scope.detail.selectedFileDrivingLicense,'DrivingLicense'),
                uploaderVehicleLicense: this.upload(this.$scope.detail.submitVehicleLicenseUrl,this.$scope.detail.selectedFileVehicleLicense,'VehicleLicense'),

                click: this.editReviseUser
            };
        });

        $("#f").bind('change', 'VehicleLicense', this.handleFileSelect);
        $('#uploaderDriving').bind('change', 'uploaderDriving', this.handleFileSelect);
        $('#idCard').bind('change', 'IDCard', this.handleFileSelect);
        $('#realHead').bind('change', 'RealHead', this.handleFileSelect);
    }
    editReviseUser() : void{
        $ngBootbox.confirm("确定保存该数据吗？").then(e =>{
            this.userService.putUserRealNameCertificationStatus(
                this.$scope.detail.userId,
                this.$scope.detail.carCode,
                this.$scope.detail.drivingLicenseCertificated,
                this.$scope.detail.realHeadImageCertificated,
                this.$scope.detail.idCardCertificated,
                this.$scope.detail.vehicleLicenseCertificated
            ).then(result => {
                this.query();
            })
        })
    }
    handleFileSelect(e: any): any{
        var files = e.target.files;
        switch (e.data) {
            case 'VehicleLicense':
                return this.$scope.detail.selectedFileVehicleLicense = files[0], 
                this.$scope.detail.submitVehicleLicenseUrl = this.handleFileSelectfunc('VehicleLicense', this.$scope.detail.selectedFileVehicleLicense.name, files); 
            case 'uploaderDriving':
                return this.$scope.detail.selectedFileDrivingLicense = files[0], 
                this.$scope.detail.submitDrivingLicenseUrl = this.handleFileSelectfunc('DrivingLicense', this.$scope.detail.selectedFileDrivingLicense.name, files);
            case 'IDCard':
                return  this.$scope.detail.selectedFileIdCard = files[0], 
                this.$scope.detail.submitIdCardUrl = this.handleFileSelectfunc('IDCard', this.$scope.detail.selectedFileIdCard.name, files);
            case 'RealHead':
                return  this.$scope.detail.selectedFileRealHead = files[0], 
                this.$scope.detail.submitRealHeadUrl = this.handleFileSelectfunc('RealHead', this.$scope.detail.selectedFileRealHead.name, files); 
        }
    }
    handleFileSelectfunc(imageName: string, name: string, files: any): any{
        var baseUrl = this.$scope.detail.sasUrl;
        var indexOfQueryStart = baseUrl.indexOf("?");
        var objUrl = this.getObjectURL(files[0]);
        
        $('#'+imageName).attr('src', objUrl);
        $('#uploader'+imageName).css('display', 'inline');
        return baseUrl.substring(0, indexOfQueryStart) + '/' + name + baseUrl.substring(indexOfQueryStart);
    }
    /**
     * 建立一個可存取到該file的url
     */
     getObjectURL(file:any):any {
        var urlImg = null;
        if (window.URL.createObjectURL != undefined) { // basic
            urlImg = window.URL.createObjectURL(file);
        } else if (window.URL != undefined) { // mozilla(firefox)
            urlImg = window.URL.createObjectURL(file);
        }
        return urlImg;
    }
    /**
     * 获取SAS url
     */
    getSasUrl(): any{
        this.storageService.AquireStorageSharedSigniture('avatar-container').then(result =>{
            return result.data.StorageSharedSigniture;
        });
    }
    /**
     * 上传
     */
    upload(submitUri:string, selectedFile:any,result:string): any{
        var _this = this;
        this.azureBlob.upload({
                baseUrl: submitUri,
                sasToken: 'avatar-container',
                file: selectedFile,
                progress: function (data, status) {
                    console.log('test progress data', data);
                    console.log('test progress status', status);
                },
                complete: function (data, status) {
                    console.log('test complete data', data);
                    console.log('test complete status', status);
                    console.info('result', result);
                    this.uploadedFun(result);
                    switch (result) {
                        case 'RealHead': return $('#RealHeadUploadSuccess').css('color', '#5CB85C'), _this.$scope.detail.realHeadImage = submitUri;
                        case 'IDCard': return $('#IDCardUploadSuccess').css('color', '#5CB85C'), _this.$scope.detail.idCardImage = submitUri;
                        case 'DrivingLicense': return $('#DrivingLicenseUploadSuccess').css('color', '#5CB85C'), _this.$scope.detail.drivingLicenseImage = submitUri;
                        case 'VehicleLicense': return $('#VehicleLicenseUploadSuccess').css('color', '#5CB85C'), _this.$scope.detail.vehicleLicenseImage = submitUri;
                    } 
                },
                error: function (xhr, desc, err) {
                    console.log('test error desc', desc);
                    console.log('test error err', err);
                },
                blockSize: 1024 * 32,
            })
    }
    /**
     * 分解roles的传值
     */
    rolesChecked(roles: any): Array<string>{
        if (Object.prototype.toString.call(roles) == "[object Null]") {
            return [];
        } else if (Object.prototype.toString.call(roles) == "[object String]") {
            return roles.split(',');
        } else if (Object.prototype.toString.call(roles) == "[object Array]") {
            return roles;
        }
    }

    /**
     * ------------------分割
     */

    /**
     * 点击事件（认证通过）
     */
    clickOk(statusValue:string):any{
        this.statePassCheck('pass',statusValue,false);
    }
    /**
     * 认证通过后 样式
     */
    clickOkPass(statusValue: string): any{
        this.statePassCheck('pass',statusValue,true);
    }
    /**
     * 点击事件（认证不通过）
     */
    clickRemove(statusValue: string):any{
        this.statePassCheck('remove',statusValue, null, false);
    }
    /**
     * 认证不通过后 样式
     */
    clickRemovePass(statusValue: string):any{
        this.statePassCheck('remove',statusValue, null, true);
    }

    /**
     * 认状态函数
     */
    statePassCheck(way: string, statusValue:string , passValue?: boolean, dispassValue?: boolean):any{
       if(statusValue == 'RealHeadImage'){
           switch(way){
               case 'pass': return this.$scope.detail.clickOkPassState = passValue;
               case 'remove': return this.$scope.detail.clickRemovePassState = dispassValue;
           }
           this.$scope.detail.realHeadImageCertificated = this.getStateResult(this.$scope.detail.clickRemovePassState, this.$scope.detail.clickOkPassState);
       }else if(statusValue == 'IDCardImage'){
           switch(way){
               case 'pass': return this.$scope.detail.clickIdCardOkPassState = passValue;
               case 'remove': return this.$scope.detail.clickIdCardRemovePassState = dispassValue;
           }
             this.$scope.detail.idCardCertificated = this.getStateResult(this.$scope.detail.clickIdCardRemovePassState, this.$scope.detail.clickIdCardOkPassState);
       }else if(statusValue == 'DrivingLicenseImage'){
           switch(way){
               case 'pass': return this.$scope.detail.clickDrivingLicenseOkPassState = passValue;
               case 'remove': return this.$scope.detail.clickDrivingLicenseRemovePassState = dispassValue;
           }
           this.$scope.detail.drivingLicenseCertificated = this.getStateResult(this.$scope.detail.clickDrivingLicenseRemovePassState, this.$scope.detail.clickDrivingLicenseOkPassState);
       }else if(statusValue == 'vehicleLicenseImage'){
           switch(way){
               case 'pass': return this.$scope.detail.clickVehicleLicenseOkPassState = passValue;
               case'remove': return this.$scope.detail.clickVehicleLicenseRemovePassState = dispassValue;
           }
            this.$scope.detail.vehicleLicenseCertificated = this.getStateResult(this.$scope.detail.clickVehicleLicenseRemovePassState, this.$scope.detail.clickVehicleLicenseOkPassState);
       }                            
    }
    
    /**
     * 实名认证状态转换（提交数据）
     */
    getStateResult(clickRemovePassState:boolean,clickOkPassState:boolean): number{
        if (clickRemovePassState == true && clickOkPassState == true) {
            return 2;
        } else if (clickRemovePassState == false) {
            return 4;
        } else if (clickOkPassState == false) {
            return 3;
        }
    };

}

app.controller('userReviseController',['$scope','userService','$ngBootbox',UserReviseController]);